package com.vincent.template.commons.base;

import com.google.common.collect.Lists;
import com.vincent.template.domain.SysUserPo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

/**
 * @author Vincent Wang
 * @date 2021/1/19 17:40
 */
public class VctUser extends User {

    private static final long serialVersionUID = 2072180895488750578L;

    private final String userId;

    public VctUser(String userId, String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
        this.userId = userId;
    }

    public String getUserId() {
        return userId;
    }

    public static UserDetails generate(SysUserPo user, VctPair<List<String>, List<String>> roleAndAuthCodes) {
        List<GrantedAuthority> authorities = Lists.newArrayList();
        // 添加角色Code
        if (CollectionUtils.isNotEmpty(roleAndAuthCodes.getLeft())) {
            roleAndAuthCodes.getLeft().forEach(code ->
                    authorities.add(new SimpleGrantedAuthority("ROLE_" + code)));
        }
        // 添加权限Code
        if (CollectionUtils.isNotEmpty(roleAndAuthCodes.getRight())) {
            roleAndAuthCodes.getRight().forEach(code ->
                    authorities.add(new SimpleGrantedAuthority(code)));
        }
        return new VctUser(user.getId(), user.getUsername(), user.getPassword(), authorities);
    }

    @Override
    public boolean equals(Object rhs) {
        return super.equals(rhs);
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }
}
